package com.example.springboot.service;

import com.example.springboot.dto.LaundryTipDTO;
import com.example.springboot.entity.LaundryTip;
import com.example.springboot.mapper.LaundryTipMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LaundryTipService {
    private static final Logger logger = LoggerFactory.getLogger(LaundryTipService.class);

    @Autowired
    private LaundryTipMapper laundryTipMapper;

    public List<LaundryTip> getActiveLaundryTips() {
        logger.info("获取所有启用的洗护小知识");
        return laundryTipMapper.findActiveTips();
    }

    public List<LaundryTip> getAllLaundryTips(String username) {
        if (!hasSuperRole(username)) {
            logger.warn("用户 {} 无超级管理员权限，无法获取所有洗护小知识", username);
            return null; // 返回 null 表示无权限
        }
        logger.info("获取所有洗护小知识（包括禁用状态）");
        return laundryTipMapper.findAll();
    }

    public LaundryTip createLaundryTip(LaundryTipDTO dto, String username) {
        if (!hasSuperRole(username)) {
            logger.warn("用户 {} 无超级管理员权限，无法创建洗护小知识", username);
            return null;
        }
        Integer adminId = laundryTipMapper.findAdminIdByUsername(username);
        if (adminId == null) {
            logger.error("未找到用户 {} 对应的管理员 ID", username);
            return null;
        }

        LaundryTip tip = new LaundryTip();
        tip.setTitle(dto.getTitle());
        tip.setContent(dto.getContent());
        tip.setCreatedBy(adminId);
        tip.setIsActive(dto.getIsActive() != null ? dto.getIsActive() : true);
        tip.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
        tip.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));

        laundryTipMapper.insert(tip);
        logger.info("成功创建洗护小知识，ID: {}", tip.getTipId());
        return tip;
    }

    public LaundryTip updateLaundryTip(Integer tipId, LaundryTipDTO dto, String username) {
        if (!hasSuperRole(username)) {
            logger.warn("用户 {} 无超级管理员权限，无法更新洗护小知识", username);
            return null;
        }

        LaundryTip tip = laundryTipMapper.findById(tipId);
        if (tip == null) {
            logger.warn("洗护小知识未找到，ID: {}", tipId);
            throw new IllegalArgumentException("洗护小知识不存在");
        }

        tip.setTitle(dto.getTitle());
        tip.setContent(dto.getContent());
        tip.setIsActive(dto.getIsActive() != null ? dto.getIsActive() : tip.getIsActive());
        tip.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));

        laundryTipMapper.update(tip);
        logger.info("成功更新洗护小知识，ID: {}", tipId);
        return tip;
    }

    public boolean deleteLaundryTip(Integer tipId, String username) {
        if (!hasSuperRole(username)) {
            logger.warn("用户 {} 无超级管理员权限，无法删除洗护小知识", username);
            return false; // 返回 false 表示无权限
        }

        LaundryTip tip = laundryTipMapper.findById(tipId);
        if (tip == null) {
            logger.warn("洗护小知识未找到，ID: {}", tipId);
            throw new IllegalArgumentException("洗护小知识不存在");
        }

        laundryTipMapper.delete(tipId);
        logger.info("成功删除洗护小知识，ID: {}", tipId);
        return true;
    }

    // 辅助方法：检查用户是否为超级管理员
    private boolean hasSuperRole(String username) {
        if (username == null) {
            return false;
        }
        String role = laundryTipMapper.findRoleByUsername(username);
        return "super".equals(role);
    }
}